package user

import (
	"context"
	"time"

	"wx_order_server/internal/svc"
	"wx_order_server/internal/types"
	"wx_order_server/internal/utils"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 登陆
func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	if req.Phone == "" || req.Password == "" {
		resp = &types.LoginResp{
			BaseResponse: types.BaseResponse{
				Code: -1,
				Msg:  "参数错误",
			},
		}
		return
	}

	findUser, _ := l.svcCtx.UserModel.GetUserInfoByPhone(l.svcCtx.DbEngin, req.Phone)

	if findUser.UserId == 0 {
		resp = &types.LoginResp{
			BaseResponse: types.BaseResponse{
				Code: -1,
				Msg:  "用户不存在",
			},
		}
		return
	}

	if !utils.CheckPassword(req.Password, findUser.PassWord) {
		resp = &types.LoginResp{
			BaseResponse: types.BaseResponse{
				Code: -1,
				Msg:  "密码错误",
			},
		}
		return
	}

	token, err := l.GenToken(findUser.UserId)

	resp = &types.LoginResp{
		BaseResponse: types.BaseResponse{
			Code: 0,
			Msg:  "请求成功",
		},
		Data: types.LoginRespBase{
			Id:    findUser.UserId,
			Name:  findUser.Phone,
			Token: token,
		},
	}

	return
}

func (l *LoginLogic) GenToken(userId int64) (string, error) {
	claims := make(jwt.MapClaims)
	iat := time.Now().Unix()

	exp := iat + l.svcCtx.Config.Auth.AccessExpire

	claims["exp"] = exp
	claims["iat"] = iat
	claims["userId"] = userId
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))
}
